package com.lst.tools.oss.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.lst.tools.basics.utils.IoUtils;
import com.lst.tools.oss.properties.OssProperties;
import com.lst.tools.oss.service.IOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.InputStream;

/**
 * 阿里云上传工具类
 *
 * @author: Frank
 * @date: 2017/12/14 16:32
 * @version: V1.0
 */
@Service
public class OssService implements IOssService {

    private static final String BASE_PROCESS = "?x-oss-process=image/format,jpg";

    @Autowired
    private OssProperties ossProperties;

    @Autowired
    private OSSClient ossClient;

    @Override
    public String getOssUrl(String url) {
        return new StringBuilder().append(ossProperties.getRealUrlBase()).append(url).toString();
    }

    @Override
    public String put(String dstKey, InputStream inputStream) {
        return this.put(dstKey, inputStream, null);
    }

    @Override
    public String put(String dstKey, InputStream inputStream, ObjectMetadata metaData) {
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossProperties.getBucKey(), dstKey, inputStream, metaData);
            return put(putObjectRequest) ? dstKey : null;
        } finally {
            IoUtils.close(inputStream);
        }
    }

    @Override
    public String put(String dstKey, File file, ObjectMetadata metaData) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(ossProperties.getBucKey(), dstKey, file, metaData);
        return put(putObjectRequest) ? dstKey : null;
    }

    /**
     * 上传
     *
     * @param request
     * @return
     */
    private boolean put(PutObjectRequest request) {
        try {
            ossClient.putObject(request);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
